package com.sa.iam.config;

import com.sa.user.api.dto.PermissionDTO;
import com.sa.user.api.dto.RoleDTO;
import com.sa.user.api.feignapi.PermissionApi;
import com.sa.user.api.feignapi.RoleApi;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Architecture Station
 * @version 1.0
 * @website 
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer {

    private final RoleApi roleApi;
    private final PermissionApi permissionApi;
    private final RedisTemplate redisTemplate;

    private

    @PostConstruct
    void init() {
        log.info("Starting data initialization...");
        try {
            // 初始化角色权限数据
            initRolePermissions();
            log.info("Data initialization completed successfully.");
        } catch (Exception e) {
            log.error("Data initialization failed: ", e);
        }
    }

    private void initRolePermissions() {
        log.info("Initializing role permissions...");
        // 查询所有角色信息
        List<RoleDTO> allRoles = roleApi.loadAllRoles();
        log.info("Loaded {} roles.", allRoles.size());

        // 通过角色ID查询角色权限信息
        for (RoleDTO roleDTO : allRoles) {
            log.info("Processing role: {}", roleDTO.getName());
            // 通过角色ID查询角色权限列表信息
            List<PermissionDTO> permissionDTOS = permissionApi.loadPermissionsByRoleId(roleDTO.getId());
            List<String> permissions = permissionDTOS.stream()
                    .map(PermissionDTO::getName)
                    .collect(Collectors.toList());
            log.info("Role {} has {} permissions.", roleDTO.getName(), permissions.size());

            // 将角色权限信息存入Redis
            try {
                // role-permissions-admin  , [ user:select,user:delete,user:update,user:create ]
                redisTemplate.opsForValue().set("role-permissions-" + roleDTO.getName(), permissions, 60 * 60 * 24, TimeUnit.SECONDS);
                log.info("Stored permissions for role {} in Redis.", roleDTO.getName());
            } catch (Exception e) {
                log.error("Failed to store permissions for role {}: ", roleDTO.getName(), e);
            }
        }
        log.info("Role permissions initialization completed.");

    }

}
